const app = getApp();
const utils = require('../../../utils/pay.js');
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    currPage: 1,
    loadingMoreHidden: 1,
    payDialog: { //代支付弹框
      isshow: false,
      ispay: false,
      title1: "",
      title2: "",
      submittext: ""
    },
    userInfo: {},
    platform: null,
    tranY: false,
    accountBalance: 0, //支付余额
    currUid: 0, //当前点击记录uid 
    currId: 0, //当前点击记录id 
    versionid: 0, //版本0个人2商家3共享4智慧经营
    discount: 0, //商家折扣
    payMoney: 0 //折扣后价格
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.discount) {
      this.setData({
        discount: options.discount
      })
    }
    this.setData({
      platform: app.globalData.platform
    })
  },

  copyData: function(e){
    let mobile = e.currentTarget.dataset.copy;
    mobile = mobile.toString();
    util.copyData(mobile,'手机号')
  },


  // 获取各个版本的价格,计算余额支付的价格；
  getPrice: function(versionid, discount) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetUpgradePrice?IndustryCode=' + versionid + '&uid=' + app.globalData.userInfo.Uid + '&payType=1',
      success: function(res) {
        let price = res.data.Data.Price;
        let payMoney = parseFloat(price * 0.01 * (100 - discount)).toFixed(2);
        that.setData({
          payMoney: payMoney
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getMyPayRequests();
  },

  // 开通名片时选择个人版或商家版
  versionSelect: function(e) {
    let versionid = e.currentTarget.dataset.versonid;
    this.getPrice(versionid, this.data.discount);
    this.setData({
      versionid: versionid
    })
  },

  //查看免费名额
  getDistributor: function(cb) {
    let that = this;
    wx.showLoading({
      title: '请求中',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributor?userId=' + app.globalData.userInfo.Uid + '&showChild=0&showGrade=0',
      success: function(res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var createStaffBalance = res.data.Data.CreateStaffBalance; //名额
          var usedStaffBalance = res.data.Data.UsedStaffBalance //已使用 
          var accountBalance = res.data.Data.AccountBalance //充值余额
          that.setData({
            accountBalance: accountBalance
          })
          cb(createStaffBalance, usedStaffBalance);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //获取待确认列表
  getMyPayRequests: function() {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetMyPayRequests?uid=' + app.globalData.userInfo.Uid + '&status=0' + '&page=' + that.data.currPage,
      success: function(res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          for (let i = 0; i < list.length; i++) {
            list[i].reqDate = list[i].RequestTime.substr(0, 10);
            list[i].reqTime = list[i].RequestTime.substr(11);
          }
          if (that.data.currPage != 1) {
            var preList = that.data.lists
            list = preList.concat(list);
          }
          that.setData({
            list: list
          })
        }
      }
    })
  },
  // 加载更多
  loadMore: function(e) {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.currPage < that.data.loadingMoreHidden) {
      var currPage = that.data.currPage;
      that.setData({
        currPage: currPage + 1
      })
      that.getMyPayRequests();
    }
  },

  /**
   * 申请列表操作
   * @param status 0待审核1审核通过2审核拒绝
   */
  changeStatus: function(e) {
    let {
      status,
      id,
      uid,
      nickname,
      avatar,
      versionid
    } = e.currentTarget.dataset;
    let {
      payDialog,
      userInfo
    } = this.data;
    if (status == 1) { //接受
      userInfo.Uid = uid;
      userInfo.NickName = nickname;
      userInfo.Avatar = avatar;
      userInfo.id = id;
      var that = this;
      that.getPrice(versionid, that.data.discount);
      that.setData({
        versionid: versionid
      })
      that.getDistributor(function(a, b) {
        payDialog.isshow = true;
        if (parseInt(a) > parseInt(b)) {
          payDialog.title1 = "您还有预充名额";
          payDialog.title2 = "使用预充名额助好友创建";
          payDialog.submittext = "马上使用";
          payDialog.staffBalance = true //是否有免费名额
        } else {
          payDialog.title1 = "您的预充名额已用完";
          payDialog.title2 = "需付费帮好友创建";
          payDialog.submittext = "确定支付";
          payDialog.staffBalance = false
        }
        that.setData({
          payDialog: payDialog,
          userInfo: userInfo
        });
      })

    } else { //拒绝
      let that = this;
      wx.showModal({
        title: '提示',
        content: '是否确定!',
        success(res) {
          if (res.confirm) {
            that.changeStatusSubmit(status, id);
          }
        }
      })
    }
  },

  //改变状态接口
  changeStatusSubmit: function(status, id) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/ChangePayRequestStatus?id=' + id + '&status=' + status,
      success: function(res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '成功'
          })
          that.getMyPayRequests();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //支付或者使用免费名额创建
  creatMyCardPay: function(e) {
    let that = this;
    let {
      uid,
      id
    } = e.currentTarget.dataset;
    var cardid = wx.getStorageSync('cardId');
    that.setData({
      currUid: uid,
      currId: id
    })
    that.getDistributor(function(a, b) {
      if (parseInt(a) > parseInt(b)) { //使用免费名额创建
        wx.request({
          url: app.globalData.host + '/api/Staff/CreateStaffUseBalance?uid=' + uid + '&shareStaffId=' + cardid + '&requestId=' + id + '&industryCode=' + that.data.versionid,
          success: function(res) {
            if (res.data.Code == 0) {
              wx.showToast({
                title: '成功'
              })
              that.dialogsState();
              that.getMyPayRequests();
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.Message,
                showCancel: false
              })
            }
          }
        })
      } else { //支付创建
        that.dialogsState();
        that.closeFooter();
      }
    })
  },

  //弹出或者关闭底部弹框
  closeFooter: function() {
    this.setData({
      tranY: !this.data.tranY
    })
  },

  //微信提交支付
  submitCreateStaffOrder: function() {
    let that = this;
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Order/SubmitCreateStaffOrder',
      data: {
        uid: that.data.userInfo.Uid, //代支付人
        shareStaffId: 0, //推荐人
        shareUid: app.globalData.userInfo.Uid, //当前人
        payRequestId: that.data.userInfo.id,
        industryCode: that.data.versionid
      },
      method: 'POST',
      success: function(res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          utils.wxpay(app, res.data.Data, 1)
          that.dialogsState();
          that.getMyPayRequests();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
          return;
        }
      },
      fail: function(err) {
        wx.showModal({
          title: '提示',
          content: res.data.Message,
          showCancel: false,
        })
        return;
      }
    })
  },

  //关闭显示弹框
  dialogsState: function() {
    let {
      payDialog
    } = this.data;
    if (payDialog.isshow) {
      payDialog.isshow = false;
    } else {
      payDialog.isshow = true;
    }
    this.setData({
      payDialog: payDialog
    })
  },

  //余额开通按钮提交
  submitBalance: function() {
    if (parseFloat(this.data.accountBalance) < parseFloat(this.data.payMoney)) { //提交申请
      this.requestAccountBalance();
    } else { //使用余额开通
      this.createStaffUseAccountBalance();
    }
  },

  //使用佣金额度创建默认名片
  createStaffUseAccountBalance: function() {
    let that = this;
    var cardid = wx.getStorageSync('cardId');
    let payMoney = that.data.payMoney;
    wx.showModal({
      title: '提示',
      content: '支付' + payMoney + '助好友开通玖玖客',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '创建中',
            mask: true
          })
          wx.request({
            url: app.globalData.host + '/api/Staff/CreateStaffUseAccountBalance',
            data: {
              uid: that.data.userInfo.Uid, //待创建名片人
              shareStaffId: cardid, //名片分享人
              requestId: that.data.userInfo.id, //申请编号
              industryCode: that.data.versionid //开通版本（个人/商家/共享/智慧经营）
            },
            method: 'POST',
            success: function(res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '成功'
                })
                that.dialogsState();
                that.getMyPayRequests()
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },

  //提交申请余额代充
  requestAccountBalance: function() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '发送升级申请，保障账户安全！\r\n运营经理会在24小时内联系您',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '申请中',
            mask: true
          })
          wx.request({
            url: app.globalData.host + '/api/Distributor/RequestAccountBalance?uid=' + app.globalData.userInfo.Uid,
            success: function(res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '成功'
                })
                that.dialogsState();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})